Lesson 7 - intermediate exercise
For each scenario write code to solve it.
Scenario - Create a simple binary calculator. It will add two binary values together and output the result. A sample run is shown below -
Enter number 1 - 10110011
Enter number 2 - 00010011
result - 11000110
.
# pad out binary number with 0's
def pad(text, amount):
for i in range (0, amount):
text = "0" + text
return text
# raw input is needed as 0001 would end up as 1!
# also they will convert to numbers
num1 = raw_input("Enter number 1-")
num2 = raw_input("Enter number 2-")
# pad out so both are the same size
# adding 0's at the front will not effect the magnitude
if len(num1) >= len (num2):
diff = len(num1) - len(num2)
num2 = pad(num2, diff)
else:
diff = len(num2) - len(num1)
num1 = pad(num1, diff)
pos = len(num1) - 1
carry = 0
output = ""
while pos >= 0:
calc = int(num1[pos]) + int(num2[pos]) + carry
if calc >= 2:
carry = 1
calc -= 2
else:
carry = 0
output = str(calc) + output
pos -= 1
if carry == 1: output = "1" + output
print "result = ", output
Toggle answer
Scenario - You have been given a large amount of coins in a black bag. You have been asked to work out what the minimum and maximum value could be by weighing the coins. You are not allowed to open the black bag!! Below is a table of coins which could be in the bag (these are made up weights!). The input will be given in grams.
Amount |
Weight |
1p |
6g |
2p |
12g |
10p |
9g |
20p |
7g |
import math
coins = [(1,6), (2,12), (10,9), (20,7)]
bag = input("Enter weight of coin bag - ")
def testCoin(coinWeight, weight):
num = weight / coinWeight
num = math.floor(num)
return num
def findValue(bagWeight):
value = 0
for i in coins:
num = testCoin(i[1], bagWeight)
bagWeight -= num * i[1]
value += num * i[0]
return value
print "min value is ", findValue(bag)
coins.reverse()
print "max value is ", findValue(bag)
Toggle answer